<?php

namespace app\api\service\live;

use app\api\model\intelligentlive\LiveData;
use app\api\model\live\LiveProducts;
use app\api\model\live\LiveProductText;
use app\api\model\live\LiveRecords;
use app\api\model\live\LiveRecordsStatus;
use app\api\model\live\LiveTips;
use app\lib\exception\live\LiveException;
use think\Db;
use think\Exception;
use think\facade\Request;

include "../vendor/PHPExcel/Classes/PHPExcel.php";
require_once '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
require_once '../vendor/PHPExcel/Classes/PHPExcel/Reader/Excel5.php';
use PHPExcel;
use PHPExcel_IOFactory;

class EventService
{
    private static $instance;

    public static function getInstance(): EventService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function records($params){
        Db::startTrans();
        try {
            $data = [
                "gmv"=>$params["gmv"],
                "amount_in_force"=>$params["amount_in_force"],
                "estimated_commission"=>$params["estimated_commission"],
                "account_name"=>$params["account_name"],
                "date"=>$params["date"],
                "person_in_charge" => $params["person_in_charge"],
                "month"=>$params["month"]
            ];
            $event = LiveRecords::where("date",$params["date"])->where("account_name",$params["account_name"])->findOrEmpty();
            if ($event->isEmpty()){
                LiveRecords::create($data);
            }else{
                LiveRecords::where("date",$params["date"])
                    ->where("account_name",$params["account_name"])
                    ->update($data);
            }
            DB::commit();

        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => '导入失败',
                'error_code' => 20002
            ]);
        }
        return $params["account_name"].$params["date"]."已采集完成";
    }

    function list($params){
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        //每天的业绩
        $day_total = LiveRecords::field("sum(gmv)as gmvTotal,sum(amount_in_force)as effectiveAmount,sum(estimated_commission)as commissionAmount,date")
            ->group("date")
            ->select()
            ->toArray();
        //每天每个账号的盈利情况
        $account_profit_request = LiveRecords::field("account_name,person_in_charge,gmv,amount_in_force,estimated_commission,date")
            ->where("date",empty($params["date"])?$yesterday:$params["date"])
            ->select()
            ->toArray();
        //月份的总业绩
        $month_total = LiveRecords::field("sum(gmv)as gmvTotal,sum(amount_in_force)as effectiveAmount,sum(estimated_commission)as commissionAmount,month")
            ->group("month")
            ->select()
            ->toArray();
        $account_commission = LiveRecords::field("sum(estimated_commission)as commissionAmount,person_in_charge")
            ->group("person_in_charge")
            ->select()
            ->toArray();
        $data = [
            "day_total" =>$day_total,
            "account"=>$account_profit_request,
            "month_performance"=>$month_total,
            "account_commission"=>$account_commission
        ];

        return $data;
    }


    public function recapture()
    {
        LiveRecordsStatus::where("id",1)->update(["status"=>1]);
    }

    public function getRecapture($params){
        if (isset($params["status"])){
            LiveRecordsStatus::where("id",1)->update(["status"=>intval($params["status"])]);
            return "重采已完成";
        }else{
            $status = LiveRecordsStatus::field("status")->where("id",1)->find();
            return $status->status;
        }
    }

    function addProducts($params){
        $data = json_decode($params['data'],true);
        $i = 0;
        $j = 0;
        $result = [];
        Db::startTrans();
        try {
            foreach ($data as $item) {
                $event = LiveProducts::where("product_id",$item["product_id"])->findOrEmpty();
                if ($event->isEmpty()){
                    LiveProducts::create($item);
                    $i++;
                }else{
                    unset($item["id"]);
                    $item["status"] = 1;
                    LiveProducts::where("product_id",$event["product_id"])
                        ->update($item);
                    $j++;
                }
            }
            $result = ["create"=>$i,"update"=>$j];
            DB::commit();

        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => '入库失败',
                'error_code' => 20002
            ]);
        }
        return $result;
    }

    public function getProductItem()
    {
        $item = LiveProducts::where('status',1)->findOrEmpty();
        if (!$item->isEmpty()){
            $item->status = 2;
            $item->save();
        }
        return $item;
    }

    public function upProductItem($params)
    {
        $result = LiveProducts::where('product_id',$params["product_id"])->findOrEmpty();
        if ($result->isEmpty()){
            throw new LiveException([
                'msg' => '无数据',
                'error_code' => 20001
            ]);
        }
        $params["status"] = 3;
        $params["week_daren_rate"] = 0;
        if (isset($params["week_daren"]) && isset($params["week_order_daren"]) && !empty($params["week_daren"]) && !empty($params["week_order_daren"])) {
            $params["week_daren_rate"] = round($params["week_order_daren"]/$params["week_daren"],2);
        }

        $res = LiveProducts::where("id", $result["id"])->update($params);
        return $res;
    }

    public function getProducts($params)
    {
        $pageSize = $params['pageSize'] ?? 50;
        $order_str = "";

        $query = new LiveProducts();

        if (isset($params['keyword']) && $params['keyword'] != "") {
            $query = $query->where('keyword', $params['keyword']);
        }

        if (isset($params['name']) && $params['name'] != "") {
            $query = $query->whereLike('name', "%".$params['name']."%");
        }

        foreach ($params["info"] as $key=>$val) {
            if ($val != 0) {
                $order_str = $key." ".($val==1?"ASC":"DESC");
                break;
            }
        }
        if ($order_str != "") {
            $query = $query->order($order_str);
        }

        $list = $query->paginate($pageSize);
        return $list;
    }

    public function importProductText($file)
    {
        $product_id = Request::param('product_id');

        $event = new LiveProductText();
//        $count = $event->where("product_id", $product_id)->count();
//        if ($count > 0) {
//            throw new LiveException(['msg' => '该商品已有话术', 'error_code' => 20001]);
//        }

        $filename  = $file->getInfo()['tmp_name'];
        //设置excel格式
        $reader = PHPExcel_IOFactory::createReader('Excel2007');
        //载⼊excel⽂件
        $excel = $reader->load($filename);
        //读取第⼀张表
        $sheet = $excel->getSheet(0);
        //获取总⾏数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = 'C';
        $datas = []; //数组形式获取表格数据
        $head = [];

        for($row=1;$row<=$row_num;$row++)
        {
            for($col='A';$col<=$col_num;$col++) {
                if ($row == 1) {
                    $head[] = $sheet->getCell($col."1")->getValue();
                } else {
                    $datas[$row-2][] = $sheet->getCell($col.$row)->getValue();
                }
            }
        }

        $array2 = ["text","path","voice_type"];
        if (array_diff_assoc($head, $array2) != NULL) {
            throw new LiveException(['msg' => '表结构不正确', 'error_code' => 20001]);
        }

        DB::startTrans();
        try {
            $save_data = [];

            for ($row = 0; $row < count($datas); $row++) {
                $add = [];
                $add["text"] = $datas[$row][0];
                $add["product_id"] = $product_id;
                $add["path"] = $datas[$row][1];
                $add["voice_type"] = $datas[$row][2];
                $add["status"] = 1;
                $save_data[] = $add;
            }

            if (count($save_data) > 0) {
                $res = $event->saveAll($save_data);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => '导表失败',
                'error_code' => 20002
            ]);
        }

        return count($res);
    }

    public function importTips($file)
    {
        $product_id = Request::param('product_id');

        $event = new LiveTips();
//        $count = $event->where("product_id", $product_id)->count();
//        if ($count > 0) {
//            throw new LiveException(['msg' => '该商品已有题词', 'error_code' => 20001]);
//        }

        $filename  = $file->getInfo()['tmp_name'];
        //设置excel格式
        $reader = PHPExcel_IOFactory::createReader('Excel2007');
        //载⼊excel⽂件
        $excel = $reader->load($filename);
        //读取第⼀张表
        $sheet = $excel->getSheet(0);
        //获取总⾏数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = 'A';
        $datas = []; //数组形式获取表格数据
        $head = [];

        for($row=1;$row<=$row_num;$row++)
        {
            for($col='A';$col<=$col_num;$col++) {
                if ($row == 1) {
                    $head[] = $sheet->getCell($col."1")->getValue();
                } else {
                    $datas[$row-2][] = $sheet->getCell($col.$row)->getValue();
                }
            }
        }

        $array2 = ["tip"];
        if (array_diff_assoc($head, $array2) != NULL) {
            throw new LiveException(['msg' => '表结构不正确', 'error_code' => 20001]);
        }

        DB::startTrans();
        try {
            $save_data = [];

            for ($row = 0; $row < count($datas); $row++) {
                $add = [];
                $add["tip"] = $datas[$row][0];
                $add["product_id"] = $product_id;
                $save_data[] = $add;
            }

            if (count($save_data) > 0) {
                $res = $event->saveAll($save_data);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => '导表失败',
                'error_code' => 20002
            ]);
        }

        return count($res);
    }
}
